package com.server.netty.simple;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @author @追风少年
 * @description
 * @date 2022/4/13
 */
public class NettyServer {

    public static void main(String[] args) throws Exception {

        /*
         * 创建两个线程组：BossGroup、WorkerGroup,
         * BossGroup 只是处理连接请求，真正和客户端进行业务处理的，会交给 WorkerGroup完成
         * 两个都是无限循环
         */
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            // 创建服务器端的启动对象，配置参数
            ServerBootstrap bootstrap = new ServerBootstrap();

            //设置
            bootstrap
                    // 设置两个线程组
                    .group(bossGroup, workerGroup)
                    // 使用 NioServerSocketChannel 作为服务器端的通道实现
                    .channel(NioServerSocketChannel.class)
                    // 设置线程队列得到连接个数
                    .option(ChannelOption.SO_BACKLOG, 128)
                    // 设置保持活动连接状态
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    // 给 WorkerGroup 的 EventLoop对应的管道设置处理器
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        // 给 pipeline 设置处理器
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new NettyServerHandler());
                        }
                    });
            System.out.println("server is ready...");

            // 绑定一个端口并且同步，生成一个 channelFuture 对象
            ChannelFuture channelFuture = bootstrap.bind(8888).sync();

            // 当通道关闭时，进行监听
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

}
